﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 资产维护提醒
    /// </summary>
    [ControllerGroup(groupName: "AssetUpkeep", useage: "资产管理-维护提醒")]
    public class AssetKeepWarnController : BaseController
    {
        private JWTPlayloadInfo playload;
        private readonly AssetKeepWarnBll _instance = AssetKeepWarnBll.Instance;

        /// <summary>
        /// 维护提醒分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="assetNo">资产编号</param>
        /// <param name="assetName">资产名称</param>
        /// <param name="person"></param>
        /// <param name="status"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="specs"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex = 1, int pageSize = 10, string assetNo = "", string assetName = "",
            string person = "", int status = -1, string startTime = "", string endTime = "", string specs = "")
        {
            var strWhere = new StringBuilder("");
            if (!string.IsNullOrEmpty(assetNo))
            {
                strWhere.Append($" and AssetNo like '%{assetNo}%'");
            }
            if (!string.IsNullOrEmpty(assetName))
            {
                strWhere.Append($" and AssetName like '%{assetName}%'");
            }
            if (!string.IsNullOrEmpty(person))
            {
                strWhere.Append($" and Person like '%{person}%'");
            }
            if (status != -1)
            {
                strWhere.Append($" and Status = {status}");
            }
            if (!string.IsNullOrEmpty(startTime))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(startTime, out DateTime parsedDate))
                {
                    strWhere.Append($" and MaintainTimeStart >= '{startTime}'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(endTime))
            {
                // 判断是否是日期格式
                if (DateTime.TryParse(endTime, out DateTime parsedDate))
                {
                    strWhere.Append($" and MaintainTimeEnd <= '{endTime}'");
                }
                else
                {
                    return JsonHelper.ErrorJson("无效的日期格式");
                }
            }
            if (!string.IsNullOrEmpty(specs))
            {
                strWhere.Append($" and Specs like '%{specs}%'");
            }

            var dt = _instance.GetPageList(pageSize, pageIndex, strWhere.ToString(), "CreateTime DESC", out int records);
            var totalPages = PageHelper.GetPageCount(pageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 派单或转单（只需传递ID, Person（人员） 和 Remark（备注） 三个字段）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DispatchOrRelay([FromBody] AssetKeepWarn model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (string.IsNullOrEmpty(model.Person))
                {
                    return JsonHelper.ErrorJson("请选择人员");
                }
                var res = _instance.DispatchOrRelay(model);
                if (res > 0)
                {

                    LogHelper.LogAction(playload, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, "派单/转单");
                    return JsonHelper.SuccessJson("派单/转单成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, "派单/转单");
                    return JsonHelper.FailJson("派单/转单失败");
                }

            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, "派单/转单");
                throw;
            }
        }


        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 4)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            var strStatus = "";

            if (status == 1)
            {
                strStatus = "审核通过";
            }

            if (status == 4)
            {
                strStatus = "审核驳回";
            }

            try
            {
                // 判断是否存在该记录
                var model = _instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在，请刷新重试");
                }

                var result = _instance.UpdateStatus(id, status, playload.UserName);
                if (result > 0)
                {
                    // 如果状态修改为 1：已完成。修改维护登记状态为‘1：已完成’;同时更新资产的维护时间为下个周期
                    if (status == 1)
                    {
                        _instance.UpdRequestWithAudit(model, playload.UserName);
                        // 更新资产的下个维护周期
                        var cycleRes = AssetInvBll.Instance.UpdAsset_MCycle(model.AssetNo);
                    }
                    LogHelper.LogAction(playload, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.SuccessJson("状态修改成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.FailJson("状态修改失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.AssetKeepWarn, Constant.ActionEnum.Edit, strStatus);
                throw;
            }
        }
    }
}
